#pragma once 
#include "data.hpp"
#include "Util.hpp"
#include <unistd.h>
using namespace shy;


extern cloud::DataManager* _data;
namespace cloud
{
  class HotManager
  {
    private:
      std::string _back_dir;
      std::string _pack_dir;
      std::string _pack_suffix;
      int _hot_time;
    private:
      bool HotJudge(const std::string &filename)
      {
        // hot return false; 
        // non hot return true; 
        FileUtil fu(filename);
        time_t last_atime = fu.LastAccessTime();
        time_t cur_time = time(nullptr);
        if (cur_time - last_atime > _hot_time)
        {
          return true;
        }
        return false;
      }
    public:
      HotManager()
      {
        Config* config = Config::GetInstance();
        _pack_dir = config->GetPackDir();
        _back_dir = config->GetBackDir();
        _pack_suffix = config->GetPackfileSuffix();
        _hot_time = config->GetHotTime();
        FileUtil tmp1(_back_dir);
        FileUtil tmp2(_pack_dir);
        tmp1.CreateDirectory();
        tmp2.CreateDirectory();
      }
      bool RunModule()
      {
        while (1)
        {  
            // 1. traverse the backup directory to get all file names 
            FileUtil fu(_back_dir);
            std::vector<std::string> arry;
            fu.ScanDirectory(arry);

            // 2. judge if the file is a non hotspot file
            for (auto a : arry)
            {
              if (HotJudge(a) == false)
              {
                continue;
              }
               BackupInfo bi;
               if(_data -> GetOneByRealPath(a , &bi) == false) 
               {
                 // we have a file but not recorded
                 bi.NewBackupInfo(a); // set a new BackupInfo 
               }
               // 3. compress the non hotspot file
               FileUtil tmp(a);
               tmp.Compress(bi.pack_path);
               // 4. delete source file and update the infomation
               tmp.Remove();
               bi.pack_flag = true;
               _data->Update(bi);
            }
            usleep(1000000);
        }
     }
  };
}


